<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>任务列表</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <$ render "common/css.html" $>
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <legend>搜索信息</legend>
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">任务名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="TaskName" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">任务状态</label>
                            <div class="layui-input-inline">
                                <select name="RunStatus">
                                    <option value="-1">请选择状态</option>
                                    <option value="0">待执行</option>
                                    <option value="1">运行中</option>
                                    <option value="2">停止</option>
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"> 添加</button>
                <button class="layui-btn layui-btn-sm layui-btn-danger data-delete-btn" lay-event="delete"> 删除</button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>
        <div id="test1"></div>

        <script type="text/html" id="currentTableBar">
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="edit">编辑</a>
            <!-- 这里同样支持 laytpl 语法，如： -->
            {{#  if(d.TaskStatus == 2){ }}
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="start">开始</a>
            {{#  } }}
            {{#  if(d.TaskStatus == 1){ }}
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-edit" lay-event="end">结束</a>
            {{#  } }}
            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">删除</a>
        </script>

    </div>
</div>
<$ render "common/js.html" $>
<script>
    layui.use(['form', 'table', 'laypage'], function () {
        var $ = layui.jquery
            , form = layui.form
            , laypage = layui.laypage
            , table = layui.table
            , currPage = 1
            , currLimit = 10;
        // 请求
        var request = function (param) {
            ajaxRequest(param, '<$ urlpath "taskList" $>')
                .then(res => {
                    if (res.code == 0) {
                        let count = res.data.count, taskList = res.data.taskList;
                        // 删除操作，判断当前页没有数据，则往前加载
                        if (count > 0 && taskList.length == 0 && currPage > 1) {
                            currPage -= 1;
                            request({'page': currPage, 'limit': currLimit});
                            return false;
                        }
                        tableOption['data'] = taskList;
                        table.render(tableOption);
                        pageOption["count"] = count;
                        pageOption["jump"] = function (obj, first) {
                            currPage = obj.curr;
                            currLimit = obj.limit;
                            //首次不执行
                            if (!first) {
                                //do something
                                request({'page': currPage, 'limit': currLimit});
                            }
                        }
                        laypage.render(pageOption);
                    }
                })
                .catch(err => {
                    console.log("error: " + err)
                });
        };
        var tableOption = {
            elem: '#currentTableId',
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {type: "checkbox", width: 50},
                {field: 'TaskId', width: 200, title: 'ID'},
                {field: 'TaskName', width: 150, title: '任务名称'},
                {field: 'TaskSpec', width: 150, title: '定时时间'},
                {field: 'TaskStatus', width: 100, title: '任务状态'},
                {field: 'TaskType', width: 100, title: '任务类型'},
                {field: 'RunCount', width: 100, title: '运行次数'},
                {field: 'RunLastTime', width: 150, title: '最后运行时间'},
                {field: 'TaskRunTime', width: 150, title: '任务执行时间'},
                {field: 'CreatedAt', width: 150, title: '创建时间'},
                {title: '操作', minWidth: 300, toolbar: '#currentTableBar', align: "center"}
            ]],
            page: false,
            skin: 'line'
        }
            , pageOption = {
            elem: 'test1'
            , curr: location.hash.replace('#!page=', '') //获取起始页
            , count: 70 //数据总数，从服务端得到
            , limits: [10, 15, 20, 25, 50, 100]
            , limit: currLimit
            , layout: ['prev', 'page', 'next', 'limit', 'count']
            , jump: function (obj, first) {
                //obj包含了当前分页的所有参数，比如：
                // console.log(obj.curr); //得到当前页，以便向服务端请求对应页的数据。
                // console.log(obj.limit); //得到每页显示的条数
                currPage = obj.curr;
                currLimit = obj.limit;
                //首次不执行
                if (!first) {
                    //do something
                    request({'page': currPage, 'limit': currLimit});
                }
            }
        };
        // 初始化加载
        request({'page': currPage, 'limit': currLimit});


        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            var result = JSON.stringify(data.field);
            // layer.alert(result, {
            //     title: '最终的搜索信息'
            // });
            let param = data.field;
            let requestParam = {'page': currPage, 'limit': currLimit, 'TaskName': param['TaskName'], 'RunStatus': param['RunStatus']};
            request(requestParam);
            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加任务',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '<$ urlpath "editTaskPage" "0"$>',
                    end: function () {
                        request({'page': currPage, 'limit': currLimit});
                    },
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                TaskIds = [];
                for (let i in data) {
                    let val = data[i];
                    TaskIds.push(val.TaskId);
                }
                if (TaskIds.length == 0) {
                    layer.msg("请选择行！");
                    return false;
                }
                layer.confirm('确定要删除嘛？', function (index) {
                    layer.close(index);
                    ajaxRequest({"TaskIds": TaskIds.toString()}, '<$ urlpath "delTask" $>')
                        .then(res => {
                            layer.msg(res.msg);
                            if (res.code == 0) {
                                request({'page': currPage, 'limit': currLimit});
                            }
                        })
                        .catch(err => {
                            console.log(err)
                        });
                });
            }
        });

        //监听表格复选框选择
        table.on('checkbox(currentTableFilter)', function (obj) {
            console.log(obj)
        });

        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            TaskId = data.TaskId;
            if (obj.event === 'edit') {
                var index = layer.open({
                    title: '编辑任务',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: ['100%', '100%'],
                    content: '<$ urlpath "editTaskPage" ""$>' + TaskId,
                    end: function () {
                        request({'page': currPage, 'limit': currLimit});
                    },
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确定要删除嘛？', function (index) {
                    // obj.del();
                    layer.close(index);
                    ajaxRequest({"TaskIds": TaskId}, '<$ urlpath "delTask" $>')
                        .then(res => {
                            layer.msg(res.msg);
                            if (res.code == 0) {
                                request({'page': currPage, 'limit': currLimit});
                            }
                        })
                        .catch(err => {
                            console.log(err)
                        });
                });
            }else if (obj.event === 'start') {
                layer.confirm('确定要操作吗？', function (index) {
                    // obj.del();
                    layer.close(index);
                    ajaxRequest({"TaskId": TaskId}, '<$ urlpath "startTask" $>')
                        .then(res => {
                            layer.msg(res.msg);
                            if (res.code == 0) {
                                request({'page': currPage, 'limit': currLimit});
                            }
                        })
                        .catch(err => {
                            console.log(err)
                        });
                });
            }else if (obj.event === 'end') {
                layer.confirm('确定要操作吗？', function (index) {
                    // obj.del();
                    layer.close(index);
                    ajaxRequest({"TaskId": TaskId}, '<$ urlpath "stopTask" $>')
                        .then(res => {
                            layer.msg(res.msg);
                            if (res.code == 0) {
                                request({'page': currPage, 'limit': currLimit});
                            }
                        })
                        .catch(err => {
                            console.log(err)
                        });
                });
            }
        });
    });
</script>

</body>
</html>